<script lang="ts" setup>
import { computed, ref, watch } from "vue";
import { useRequest } from "vue-request";
import service from "@/services/request";
const prefix = `${import.meta.env.VITE_API_PREFIX}`;

const emits = defineEmits(["update:modelValue", "change"]);

const props = defineProps({
  modelValue: {
    type: [Number, String, Array],
  },
  request: {
    type: Object,
    default: () => {
      return {
        url: "",
        method: "GET",
        params: {},
      };
    },
  },
  props: {
    type: Object,
    default: () => {
      return {
        label: "label",
        value: "value",
        key: "id",
        des: "",
      };
    },
  },
});

const searchKey = ref<string>("");
const value = ref(props.modelValue);

// 监听 modelValue 属性，给 value 赋值
watch(
  () => props.modelValue,
  (v1) => {
    value.value = v1;
  },
);

const vChange = (value: string) => {
  // 修改 modelValue 属性
  emits("update:modelValue", value);
  // 选择类需要的事件
  emits("change", value);
};

const getList = (requestConf: any, params: any) => {
  return service({
    url: `${prefix}${requestConf.url}`,
    method: requestConf.method,
    params: {
      ...requestConf.params,
      ...params,
    },
  });
};

const { run, data, loading } = useRequest(getList, {
  manual: true,
});

if (value.value) {
  run(props.request, {
    [props.props.key]: value.value,
  });
}

const options = computed(() => {
  if (searchKey.value === "" && !value.value) return [];
  return data.value?.data || [];
});

const remoteMethod = (query: string) => {
  searchKey.value = query;
  if (query) {
    run(props.request, {
      searchKey: query,
    });
  }
};
</script>

<template>
  <el-select
    style="width: 100%"
    v-model="value"
    filterable
    remote
    reserve-keyword
    :remote-method="remoteMethod"
    :loading="loading"
    suffix-icon="Search"
    remote-show-suffix
    clearable
    @change="vChange"
  >
    <el-option
      v-for="item in options"
      :key="item[props.props.value || 'value']"
      :label="item[props.props.label || 'label']"
      :value="item[props.props.value || 'value']"
    >
      <span style="float: left">{{ item[props.props.label || "label"] }}</span>
      <span
        v-if="props.props.des"
        style="
          float: right;
          color: var(--el-text-color-secondary);
          font-size: 13px;
        "
        >{{ item[props.props.des || "des"] }}</span
      >
    </el-option>
  </el-select>
</template>
